package top.kent90.controller;


import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import top.kent90.common.object.AjaxDone;
import top.kent90.common.object.Result;
import top.kent90.common.object.ZTreeNode;
import top.kent90.pojo.SysRoleRights;
import top.kent90.pojo.SysRoles;
import top.kent90.service.SysRolesService;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("role")
public class SysRolesController {
    @Reference
    SysRolesService service;
    @RequestMapping("toRoles")
    public String toRoles(){
        return "role/index";
    }
    @RequestMapping("toAddRole")
    public String toAddRole(){return "role/addRole";}
    @RequestMapping("toSetRights")
    public ModelAndView toSetRights(@ModelAttribute("id") String id){
        ModelAndView model = new ModelAndView();
        model.setViewName("role/setRights");
        model.addObject("id",id);
        return model;
    }
    @RequestMapping("rolesList")
    @ResponseBody
    public Result roleList(HttpServletRequest request){
        //获取页码
        String pageNum = request.getParameter("page");
        //获取显示条数
        String pageSize = request.getParameter("limit");
        Result rs = service.queryRoles(null,pageNum,pageSize);
        return rs;
    }
//    @RequestMapping("queryPopedom")
//    @ResponseBody
//    public AjaxDone queryPopedom(HttpServletRequest request){
//       String id = request.getParameter("id");
//       List<> service.queryPopedom(id);
//    }
@ResponseBody
@RequestMapping("queryPopedom")
public List<ZTreeNode> queryPopedom(HttpServletRequest request, HttpServletResponse response){
    String roleId = request.getParameter("roleId");
    try{
        List<ZTreeNode> ztn = service.createTree(roleId);
        return ztn;
    } catch(Exception e){
        e.printStackTrace();
    }
    return null;
}
    /**
     * 保存角色授权 权限信息
     * @return
     */
    @ResponseBody
    @RequestMapping("saveRolesPopedom")
    public AjaxDone saveRolesPopedom(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("roleId");
        String popedom = request.getParameter("ids");

        try{
            Integer  roleId = Integer.parseInt(id);
            String[] popedomIds = popedom.split(",");
            List<SysRoleRights> list = new ArrayList<SysRoleRights>();

            if(!"".equals(popedom)){
                for (String popedomId : popedomIds) {
                    SysRoleRights srr = new SysRoleRights();
                    srr.setRoleId(roleId);
                    srr.setPopedomId(Integer.parseInt(popedomId));
//                    srr.setCreateTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss ").format(new Date()));
//                    srr.setCreateUserId(getLoginObject(request).getUserId());
//                    srr.setCreateUserName(getLoginObject(request).getUserName());
                    list.add(srr);
                }
            }
            int rst = service.savePopedomRoles(roleId, list);
            if(rst>0) {
                /**
                 * 1. 同时查询当前角色对应的后台管理用户的userId <br/>
                 * 2. 循环遍历每一个后台管理员用户，查询出每个后台管理员用户对应的权限信息（修改角色权限后的状态）<br/>
                 * 3. 从Application对象中找出每个后台用户对应的session对象，重置session对象中的权限信息，
                 * 	     如果找不到session对象（该用户未登录）返回null，不做操作<br/>
                 */
                List<Map<String, Object>> sruList = service.queryRoleUser(roleId);
//                for (Map<String, Object> sru : sruList) {
//                    // 从Application对象中取得对应用户的session信息，如果取不到则返回session对象为null
//                    // 如果后台用户权限被重新设定则立即刷新对应在线用户的权限session信息
//                    String userId =	String.valueOf(sru.get("user_id"));
//                    HttpSession session = (HttpSession) request.getSession().getServletContext().getAttribute(userId);
//                    if (session != null) {
//                        Map<String, String> popedomMap = loginService.queryUserRights(Integer.parseInt(userId));
//                        session.setAttribute(USER_POPEDOM_KEY, popedomMap);
//                    }
//                }
                return new AjaxDone("200", "请求成功");
            }


        } catch(Exception e){
            e.printStackTrace();
        }
        return new AjaxDone("300", "系统繁忙,请稍后再试!");
    }

    /**
     * 删除角色
     * @param request
     * @return
     */
    @RequestMapping("delRole")
    @ResponseBody
        public AjaxDone delRole(HttpServletRequest request){

        String roleid = request.getParameter("id");
        int rst = service.delRole(roleid);
        System.out.println(rst);
        if (rst>0){
            return new AjaxDone("200","请求成功");
        }else {
            return new AjaxDone("300","删除失败");

        }

    }
    @RequestMapping("addRole")
    @ResponseBody
    public AjaxDone addRole(HttpServletRequest request){
        String roleName = request.getParameter("roleName");
        System.out.println(roleName);
        SysRoles sysRole = new SysRoles();
        sysRole.setRoleName(roleName);
        //获取当前登录用户名称
//      sysRole.setCreateUserName(getLoginObject(request).getUserName());

       int rst =  service.addRole(sysRole);
       if(rst>0){
           return new AjaxDone("200","请求成功");
       }else {
           return new AjaxDone("300","删除失败");

       }
    }

}
